package com.mulei.okhttp;

import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

public class OKHttpUtils {
    public static final MediaType APPLICATION_JSON = MediaType.get("application/json");

    public static String request(OkHttpClient client, String method, String uri, String body) {
        Request.Builder builder = new Request.Builder()
                .url(uri);
        if (StringUtils.isNoneBlank(body)) {
            builder.method(StringUtils.upperCase(method), RequestBody.create(APPLICATION_JSON, body));
        } else {
            builder.method(StringUtils.upperCase(method), StringUtils.equalsIgnoreCase(method, "get") ? null : RequestBody.create(new byte[0]));
        }
        Request build = builder.build();
        try {
            Response execute = client.newCall(build).execute();
            if (execute != null && execute.isSuccessful()) {
                return execute.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }
}
